require   'rubygems'
require_gem 'activerecord'
require   'time'


class Workspace < ActiveRecord::Base
	has_and_belongs_to_many :projects
end

class Project < ActiveRecord::Base
	has_and_belongs_to_many :workspaces
	has_many :tasks, :order => 'position' 
end

class Task < ActiveRecord::Base
	belongs_to :project
	has_many :time_ranges
	belongs_to :running_range

	@@running_tasks = {}
	def self.running_tasks
		@@running_tasks.keys
	end


	def today
		total_seconds = 0
		now = Time.now
		today = Time.local(now.year, now.month, now.day)
		time_ranges.each {|range| total_seconds += range.elapsed_seconds if range.start_as_time > today}
		total_seconds += running_range.elapsed_seconds if running_range
		total_seconds
	end

	def total
		0
	end

	def start
		unless running_range
			time = Time.now
			Task.transaction do
				self.running_range = RunningRange.new
				self.running_range.start_as_time = time
				self.running_range.last_checkpoint_as_time = time
				save!
				@@running_tasks[self] = time
			end
		end
	end

	def stop(description)
		if running_range
			Task.transaction do
				range = TimeRange.new(:description => description, :task => self)
				range.start_as_time = running_range.start_as_time 
				range.end_as_time =  Time.now

				running_range.destroy
				self.running_range = nil
				range.save!
				save!				
				@@running_tasks.delete(self)
			end
		end
	end
end

class TimeRange < ActiveRecord::Base
	belongs_to :task

	def elapsed_seconds
		start_as_time - end_as_time
	end
	
	def start_as_time
		Time.parse(start_time)
	end

	def start_as_time=(time)
		self.start_time = time.to_s
	end
	
	def end_as_time
		Time.parse(end_time)
	end

	def end_as_time=(time)
		self.end_time = time.to_s
	end
end

class RunningRange < ActiveRecord::Base
	has_one :task
	
	def elapsed_seconds
		start_as_time - Time.now
	end
	
	def start_as_time
		Time.parse(start_time)
	end

	def start_as_time=(time)
		self.start_time = time.to_s
	end

	def last_checkpoint_as_time
		Time.parse(last_checkpoint)
	end

	def last_checkpoint_as_time=(time)
		self.last_checkpoint = time.to_s
	end
end
